package org.koyad.portal.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.utils.LogUtils;

@WebFilter (
		filterName = "PistonFilter", 
		urlPatterns = {
			"/" + FrameworkConstants.PISTON_FWK
		}
)
public class PistonFilter extends BaseFilter {

	private static final LogUtils LOGGER = LogUtils.getLogger(PistonFilter.class);

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		
		LOGGER.startMethod("doFilter");
		
		try {
			
			super.doFilter(req, resp, chain);
			
			HttpServletRequest httpReq = (HttpServletRequest)req;
			HttpServletResponse httpResp = (HttpServletResponse)resp;
			
			if(!httpReq.isRequestedSessionIdValid()) {
				PageUtils.setLogin(httpReq, httpResp);
			}
			
			chain.doFilter(req, resp);

		} catch (FrameworkException e) {
			LOGGER.logException(e);
			RequestDispatcher reqDisp = req.getRequestDispatcher("/Error.html");
			reqDisp.include(req, resp);
		}
		
		LOGGER.endMethod("doFilter");

	}

}
